package com.doit.day01;

import java.sql.*;
import java.util.HashMap;

public class _01_缓存伪代码 {
    static HashMap<Integer, String> map = new HashMap<>();
    public static void main(String[] args) throws SQLException {
        //2.获得连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
        //3.获取数据库操作对象
        for (int i = 0; i < 10000; i++) {
            System.out.println(getName(conn, i));
        }
        //6.释放资源
        conn.close();
    }

    public static String getName(Connection conn,int id) throws SQLException {
        String name = "";
        String res = map.get(id);
        if (res != null){
            return res;
        }else {
            PreparedStatement pps = conn.prepareStatement("select name from table where id = ?");
            //4.执行sql
            pps.setInt(1,id);
            ResultSet resultSet = pps.executeQuery();
            //5.处理查询结果集
            while (resultSet.next()){
                name = resultSet.getString(1);
            }
            //如果缓存里面没有的话，就从数据库中查，并且将查询的结果放在缓存系统中，便于下次复用
            map.put(id,name);
            return name;
        }
    }
}
